import React from 'react';
import {
  IonItem,
  IonLabel,
  IonButtons,
  IonButton,
  IonIcon,
} from '@ionic/react';
import {
  volumeHigh,
  copyOutline,
  shareOutline,
  thumbsUpOutline,
  thumbsDownOutline,
} from 'ionicons/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { TranslatorService } from '../../services/translator.service';

interface ChatMessageProps {
  text: string;
  isBot: boolean;
  isSpeakerOn: boolean;
}

const ChatMessage: React.FC<ChatMessageProps> = ({
  text,
  isBot,
  isSpeakerOn,
}) => {
  const [isCopied, setIsCopied] = React.useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy text:', err);
    }
  };

  const handleSpeak = async () => {
    if (isSpeakerOn) {
      await TranslatorService.textToSpeech(text);
    }
  };

  return (
    <IonItem lines="none" className={isBot ? 'bot-message' : 'user-message'}>
      <IonLabel className="ion-text-wrap">
        {isBot ? (
          <ReactMarkdown remarkPlugins={[remarkGfm]}>
            {text}
          </ReactMarkdown>
        ) : (
          <p>{text}</p>
        )}
      </IonLabel>
      
      {isBot && (
        <IonButtons slot="end">
          <IonButton onClick={handleSpeak} disabled={!isSpeakerOn}>
            <IonIcon icon={volumeHigh} />
          </IonButton>
          <IonButton onClick={handleCopy}>
            <IonIcon icon={copyOutline} />
          </IonButton>
          <IonButton>
            <IonIcon icon={shareOutline} />
          </IonButton>
          <IonButton>
            <IonIcon icon={thumbsUpOutline} />
          </IonButton>
          <IonButton>
            <IonIcon icon={thumbsDownOutline} />
          </IonButton>
        </IonButtons>
      )}
    </IonItem>
  );
};

export default ChatMessage;